home *** CD-ROM | disk | FTP | other *** search
/ MacAddict 108 / MacAddict108.iso / Software / Internet & Communication / WordPress 1.5.1.dmg / wordpress / wp-includes / functions.php < prev    next >
Encoding:
PHP Script  |  2005-05-03  |  51.8 KB  |  1,881 lines

  1. <?php
  2.  
  3. require_once(dirname(__FILE__).'/functions-compat.php');
  4.  
  5. if (!function_exists('_')) {
  6.     function _($string) {
  7.         return $string;
  8.     }
  9. }
  10.  
  11. function get_profile($field, $user = false) {
  12.     global $wpdb;
  13.     if (!$user)
  14.         $user = $wpdb->escape($_COOKIE['wordpressuser_' . COOKIEHASH]);
  15.     return $wpdb->get_var("SELECT $field FROM $wpdb->users WHERE user_login = '$user'");
  16. }
  17.  
  18. function mysql2date($dateformatstring, $mysqlstring, $translate = true) {
  19.     global $month, $weekday, $month_abbrev, $weekday_abbrev;
  20.     $m = $mysqlstring;
  21.     if (empty($m)) {
  22.         return false;
  23.     }
  24.     $i = mktime(substr($m,11,2),substr($m,14,2),substr($m,17,2),substr($m,5,2),substr($m,8,2),substr($m,0,4)); 
  25.     if (!empty($month) && !empty($weekday) && $translate) {
  26.         $datemonth = $month[date('m', $i)];
  27.         $datemonth_abbrev = $month_abbrev[$datemonth];
  28.         $dateweekday = $weekday[date('w', $i)];
  29.         $dateweekday_abbrev = $weekday_abbrev[$dateweekday];         
  30.         $dateformatstring = ' '.$dateformatstring;
  31.         $dateformatstring = preg_replace("/([^\\\])D/", "\\1".backslashit($dateweekday_abbrev), $dateformatstring);
  32.         $dateformatstring = preg_replace("/([^\\\])F/", "\\1".backslashit($datemonth), $dateformatstring);
  33.         $dateformatstring = preg_replace("/([^\\\])l/", "\\1".backslashit($dateweekday), $dateformatstring);
  34.         $dateformatstring = preg_replace("/([^\\\])M/", "\\1".backslashit($datemonth_abbrev), $dateformatstring);
  35.     
  36.         $dateformatstring = substr($dateformatstring, 1, strlen($dateformatstring)-1);
  37.     }
  38.     $j = @date($dateformatstring, $i);
  39.     if (!$j) {
  40.     // for debug purposes
  41.     //    echo $i." ".$mysqlstring;
  42.     }
  43.     return $j;
  44. }
  45.  
  46. function current_time($type, $gmt = 0) {
  47.     switch ($type) {
  48.         case 'mysql':
  49.             if ($gmt) $d = gmdate('Y-m-d H:i:s');
  50.             else $d = gmdate('Y-m-d H:i:s', (time() + (get_settings('gmt_offset') * 3600)));
  51.             return $d;
  52.             break;
  53.         case 'timestamp':
  54.             if ($gmt) $d = time();
  55.             else $d = time() + (get_settings('gmt_offset') * 3600);
  56.             return $d;
  57.             break;
  58.     }
  59. }
  60.  
  61. function date_i18n($dateformatstring, $unixtimestamp) {
  62.     global $month, $weekday, $month_abbrev, $weekday_abbrev;
  63.     $i = $unixtimestamp; 
  64.     if ((!empty($month)) && (!empty($weekday))) {
  65.         $datemonth = $month[date('m', $i)];
  66.         $datemonth_abbrev = $month_abbrev[$datemonth];
  67.         $dateweekday = $weekday[date('w', $i)];
  68.         $dateweekday_abbrev = $weekday_abbrev[$dateweekday];         
  69.         $dateformatstring = ' '.$dateformatstring;
  70.         $dateformatstring = preg_replace("/([^\\\])D/", "\\1".backslashit($dateweekday_abbrev), $dateformatstring);
  71.         $dateformatstring = preg_replace("/([^\\\])F/", "\\1".backslashit($datemonth), $dateformatstring);
  72.         $dateformatstring = preg_replace("/([^\\\])l/", "\\1".backslashit($dateweekday), $dateformatstring);
  73.         $dateformatstring = preg_replace("/([^\\\])M/", "\\1".backslashit($datemonth_abbrev), $dateformatstring);
  74.         $dateformatstring = substr($dateformatstring, 1, strlen($dateformatstring)-1);
  75.     }
  76.     $j = @date($dateformatstring, $i);
  77.     return $j;
  78.     }
  79.  
  80. function get_weekstartend($mysqlstring, $start_of_week) {
  81.     $my = substr($mysqlstring,0,4);
  82.     $mm = substr($mysqlstring,8,2);
  83.     $md = substr($mysqlstring,5,2);
  84.     $day = mktime(0,0,0, $md, $mm, $my);
  85.     $weekday = date('w',$day);
  86.     $i = 86400;
  87.  
  88.     if ($weekday < get_settings('start_of_week'))
  89.         $weekday = 7 - (get_settings('start_of_week') - $weekday);
  90.  
  91.     while ($weekday > get_settings('start_of_week')) {
  92.         $weekday = date('w',$day);
  93.         if ($weekday < get_settings('start_of_week'))
  94.             $weekday = 7 - (get_settings('start_of_week') - $weekday);
  95.  
  96.         $day = $day - 86400;
  97.         $i = 0;
  98.     }
  99.     $week['start'] = $day + 86400 - $i;
  100.     //$week['end']   = $day - $i + 691199;
  101.     $week['end'] = $week['start'] + 604799;
  102.     return $week;
  103. }
  104.  
  105. function get_lastpostdate($timezone = 'server') {
  106.     global $cache_lastpostdate, $pagenow, $wpdb;
  107.     $add_seconds_blog = get_settings('gmt_offset') * 3600;
  108.     $add_seconds_server = date('Z');
  109.     $now = current_time('mysql', 1);
  110.     if ( !isset($cache_lastpostdate[$timezone]) ) {
  111.         switch(strtolower($timezone)) {
  112.             case 'gmt':
  113.                 $lastpostdate = $wpdb->get_var("SELECT post_date_gmt FROM $wpdb->posts WHERE post_date_gmt <= '$now' AND post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT 1");
  114.                 break;
  115.             case 'blog':
  116.                 $lastpostdate = $wpdb->get_var("SELECT post_date FROM $wpdb->posts WHERE post_date_gmt <= '$now' AND post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT 1");
  117.                 break;
  118.             case 'server':
  119.                 $lastpostdate = $wpdb->get_var("SELECT DATE_ADD(post_date_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_date_gmt <= '$now' AND post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT 1");
  120.                 break;
  121.         }
  122.         $cache_lastpostdate[$timezone] = $lastpostdate;
  123.     } else {
  124.         $lastpostdate = $cache_lastpostdate[$timezone];
  125.     }
  126.     return $lastpostdate;
  127. }
  128.  
  129. function get_lastpostmodified($timezone = 'server') {
  130.     global $cache_lastpostmodified, $pagenow, $wpdb;
  131.     $add_seconds_blog = get_settings('gmt_offset') * 3600;
  132.     $add_seconds_server = date('Z');
  133.     $now = current_time('mysql', 1);
  134.     if ( !isset($cache_lastpostmodified[$timezone]) ) {
  135.         switch(strtolower($timezone)) {
  136.             case 'gmt':
  137.                 $lastpostmodified = $wpdb->get_var("SELECT post_modified_gmt FROM $wpdb->posts WHERE post_modified_gmt <= '$now' AND post_status = 'publish' ORDER BY post_modified_gmt DESC LIMIT 1");
  138.                 break;
  139.             case 'blog':
  140.                 $lastpostmodified = $wpdb->get_var("SELECT post_modified FROM $wpdb->posts WHERE post_modified_gmt <= '$now' AND post_status = 'publish' ORDER BY post_modified_gmt DESC LIMIT 1");
  141.                 break;
  142.             case 'server':
  143.                 $lastpostmodified = $wpdb->get_var("SELECT DATE_ADD(post_modified_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_modified_gmt <= '$now' AND post_status = 'publish' ORDER BY post_modified_gmt DESC LIMIT 1");
  144.                 break;
  145.         }
  146.         $lastpostdate = get_lastpostdate($timezone);
  147.         if ($lastpostdate > $lastpostmodified) {
  148.             $lastpostmodified = $lastpostdate;
  149.         }
  150.         $cache_lastpostmodified[$timezone] = $lastpostmodified;
  151.     } else {
  152.         $lastpostmodified = $cache_lastpostmodified[$timezone];
  153.     }
  154.     return $lastpostmodified;
  155. }
  156.  
  157. function user_pass_ok($user_login,$user_pass) {
  158.     global $cache_userdata;
  159.     if ( empty($cache_userdata[$user_login]) ) {
  160.         $userdata = get_userdatabylogin($user_login);
  161.     } else {
  162.         $userdata = $cache_userdata[$user_login];
  163.     }
  164.     return (md5($user_pass) == $userdata->user_pass);
  165. }
  166.  
  167.  
  168. function get_usernumposts($userid) {
  169.     global $wpdb;
  170.     return $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = '$userid' AND post_status = 'publish'");
  171. }
  172.  
  173. // examine a url (supposedly from this blog) and try to
  174. // determine the post ID it represents.
  175. function url_to_postid($url = '') {
  176.     global $wpdb;
  177.  
  178.     $siteurl = get_settings('home');
  179.     // Take a link like 'http://example.com/blog/something'
  180.     // and extract just the '/something':
  181.     $uri = preg_replace("#$siteurl#i", '', $url);
  182.  
  183.     // on failure, preg_replace just returns the subject string
  184.     // so if $uri and $siteurl are the same, they didn't match:
  185.     if ($uri == $siteurl) 
  186.         return 0;
  187.         
  188.     // First, check to see if there is a 'p=N' or 'page_id=N' to match against:
  189.     preg_match('#[?&](p|page_id)=(\d+)#', $uri, $values);
  190.     $p = intval($values[2]);
  191.     if ($p) return $p;
  192.     
  193.     // Match $uri against our permalink structure
  194.     $permalink_structure = get_settings('permalink_structure');
  195.     
  196.     // Matt's tokenizer code
  197.     $rewritecode = array(
  198.         '%year%',
  199.         '%monthnum%',
  200.         '%day%',
  201.         '%hour%',
  202.         '%minute%',
  203.         '%second%',
  204.         '%postname%',
  205.         '%post_id%'
  206.     );
  207.     $rewritereplace = array(
  208.         '([0-9]{4})?',
  209.         '([0-9]{1,2})?',
  210.         '([0-9]{1,2})?',
  211.         '([0-9]{1,2})?',
  212.         '([0-9]{1,2})?',
  213.         '([0-9]{1,2})?',
  214.         '([_0-9a-z-]+)?',
  215.         '([0-9]+)?'
  216.     );
  217.  
  218.     // Turn the structure into a regular expression
  219.     $matchre = str_replace('/', '/?', $permalink_structure);
  220.     $matchre = str_replace($rewritecode, $rewritereplace, $matchre);
  221.  
  222.     // Extract the key values from the uri:
  223.     preg_match("#$matchre#",$uri,$values);
  224.  
  225.     // Extract the token names from the structure:
  226.     preg_match_all("#%(.+?)%#", $permalink_structure, $tokens);
  227.  
  228.     for($i = 0; $i < count($tokens[1]); $i++) {
  229.         $name = $tokens[1][$i];
  230.         $value = $values[$i+1];
  231.  
  232.         // Create a variable named $year, $monthnum, $day, $postname, or $post_id:
  233.         $$name = $value;
  234.     }
  235.     
  236.     // If using %post_id%, we're done:
  237.     if (intval($post_id)) return intval($post_id);
  238.     
  239.     // Otherwise, build a WHERE clause, making the values safe along the way:
  240.     if ($year) $where .= " AND YEAR(post_date) = '" . intval($year) . "'";
  241.     if ($monthnum) $where .= " AND MONTH(post_date) = '" . intval($monthnum) . "'";
  242.     if ($day) $where .= " AND DAYOFMONTH(post_date) = '" . intval($day) . "'";
  243.     if ($hour) $where .= " AND HOUR(post_date) = '" . intval($hour) . "'";
  244.     if ($minute) $where .= " AND MINUTE(post_date) = '" . intval($minute) . "'";
  245.     if ($second) $where .= " AND SECOND(post_date) = '" . intval($second) . "'";
  246.     if ($postname) $where .= " AND post_name = '" . $wpdb->escape($postname) . "' ";
  247.  
  248.     // We got no indication, so we return false:
  249.     if (!strlen($where)) {
  250.         return false;
  251.     }
  252.  
  253.     // if all we got was a postname, it's probably a page, so we'll want to check for a possible subpage
  254.     if ($postname && !$year && !$monthnum && !$day && !$hour && !$minute && !$second) {
  255.     $postname = rtrim(strstr($uri, $postname), '/');
  256.     $uri_array = explode('/', $postname);
  257.     $postname = $uri_array[count($uri_array) - 1];
  258.     $where = " AND post_name = '" . $wpdb->escape($postname) . "' ";
  259.     }
  260.     
  261.     // Run the query to get the post ID:
  262.     $id = intval($wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE 1 = 1 " . $where));
  263.  
  264.     return $id;
  265. }
  266.  
  267.  
  268. /* Options functions */
  269.  
  270. function get_settings($setting) {
  271.   global $wpdb, $cache_settings, $cache_nonexistantoptions;
  272.     if ( strstr($_SERVER['REQUEST_URI'], 'wp-admin/install.php') || defined('WP_INSTALLING') )
  273.         return false;
  274.  
  275.     if ( empty($cache_settings) )
  276.         $cache_settings = get_alloptions();
  277.  
  278.     if ( empty($cache_nonexistantoptions) )
  279.         $cache_nonexistantoptions = array();
  280.  
  281.     if ('home' == $setting && '' == $cache_settings->home)
  282.         return apply_filters('option_' . $setting, $cache_settings->siteurl);
  283.  
  284.     if ( isset($cache_settings->$setting) ) :
  285.         return apply_filters('option_' . $setting, $cache_settings->$setting);
  286.     else :
  287.         // for these cases when we're asking for an unknown option
  288.         if ( isset($cache_nonexistantoptions[$setting]) )
  289.             return false;
  290.  
  291.         $option = $wpdb->get_var("SELECT option_value FROM $wpdb->options WHERE option_name = '$setting'");
  292.  
  293.         if (!$option) :
  294.             $cache_nonexistantoptions[$setting] = true;
  295.             return false;
  296.         endif;
  297.  
  298.         @ $kellogs = unserialize($option);
  299.         if ($kellogs !== FALSE)
  300.             return apply_filters('option_' . $setting, $kellogs);
  301.         else return apply_filters('option_' . $setting, $option);
  302.     endif;
  303. }
  304.  
  305. function get_option($option) {
  306.     return get_settings($option);
  307. }
  308.  
  309. function form_option($option) {
  310.     echo htmlspecialchars( get_option($option), ENT_QUOTES );
  311. }
  312.  
  313. function get_alloptions() {
  314.     global $wpdb, $wp_queries;
  315.     $wpdb->hide_errors();
  316.     if (!$options = $wpdb->get_results("SELECT option_name, option_value FROM $wpdb->options WHERE autoload = 'yes'")) {
  317.         $options = $wpdb->get_results("SELECT option_name, option_value FROM $wpdb->options");
  318.     }
  319.     $wpdb->show_errors();
  320.  
  321.     foreach ($options as $option) {
  322.         // "When trying to design a foolproof system, 
  323.         //  never underestimate the ingenuity of the fools :)" -- Dougal
  324.         if ('siteurl' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
  325.         if ('home' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
  326.         if ('category_base' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
  327.         @ $value = unserialize($option->option_value);
  328.         if ($value === FALSE)
  329.             $value = $option->option_value;
  330.         $all_options->{$option->option_name} = apply_filters('pre_option_' . $option->option_name, $value);
  331.     }
  332.     return apply_filters('all_options', $all_options);
  333. }
  334.  
  335. function update_option($option_name, $newvalue) {
  336.     global $wpdb, $cache_settings;
  337.     if ( is_array($newvalue) || is_object($newvalue) )
  338.         $newvalue = serialize($newvalue);
  339.  
  340.     $newvalue = trim($newvalue); // I can't think of any situation we wouldn't want to trim
  341.  
  342.     // If the new and old values are the same, no need to update.
  343.     if ($newvalue == get_option($option_name)) {
  344.         return true;
  345.     }
  346.  
  347.     // If it's not there add it
  348.     if ( !$wpdb->get_var("SELECT option_name FROM $wpdb->options WHERE option_name = '$option_name'") )
  349.         add_option($option_name);
  350.  
  351.     $newvalue = $wpdb->escape($newvalue);
  352.     $wpdb->query("UPDATE $wpdb->options SET option_value = '$newvalue' WHERE option_name = '$option_name'");
  353.     $cache_settings = get_alloptions(); // Re cache settings
  354.     return true;
  355. }
  356.  
  357.  
  358. // thx Alex Stapleton, http://alex.vort-x.net/blog/
  359. function add_option($name, $value = '', $description = '', $autoload = 'yes') {
  360.     global $wpdb;
  361.     $original = $value;
  362.     if ( is_array($value) || is_object($value) )
  363.         $value = serialize($value);
  364.  
  365.     if( !$wpdb->get_var("SELECT option_name FROM $wpdb->options WHERE option_name = '$name'") ) {
  366.         $name = $wpdb->escape($name);
  367.         $value = $wpdb->escape($value);
  368.         $description = $wpdb->escape($description);
  369.         $wpdb->query("INSERT INTO $wpdb->options (option_name, option_value, option_description, autoload) VALUES ('$name', '$value', '$description', '$autoload')");
  370.  
  371.         if($wpdb->insert_id) {
  372.             global $cache_settings;
  373.             $cache_settings->{$name} = $original;
  374.         }
  375.     }
  376.     return;
  377. }
  378.  
  379. function delete_option($name) {
  380.     global $wpdb;
  381.     // Get the ID, if no ID then return
  382.     $option_id = $wpdb->get_var("SELECT option_id FROM $wpdb->options WHERE option_name = '$name'");
  383.     if (!$option_id) return false;
  384.     $wpdb->query("DELETE FROM $wpdb->options WHERE option_name = '$name'");
  385.     return true;
  386. }
  387.  
  388. function add_post_meta($post_id, $key, $value, $unique = false) {
  389.     global $wpdb;
  390.     
  391.     if ($unique) {
  392.         if( $wpdb->get_var("SELECT meta_key FROM $wpdb->postmeta WHERE meta_key
  393. = '$key' AND post_id = '$post_id'") ) {
  394.             return false;
  395.         }
  396.     }
  397.  
  398.     $wpdb->query("INSERT INTO $wpdb->postmeta
  399.                                 (post_id,meta_key,meta_value) 
  400.                                 VALUES ('$post_id','$key','$value')
  401.                         ");
  402.     
  403.     return true;
  404. }
  405.  
  406. function delete_post_meta($post_id, $key, $value = '') {
  407.     global $wpdb;
  408.  
  409.     if (empty($value)) {
  410.         $meta_id = $wpdb->get_var("SELECT meta_id FROM $wpdb->postmeta WHERE
  411. post_id = '$post_id' AND meta_key = '$key'");
  412.     } else {
  413.         $meta_id = $wpdb->get_var("SELECT meta_id FROM $wpdb->postmeta WHERE
  414. post_id = '$post_id' AND meta_key = '$key' AND meta_value = '$value'");
  415.     }
  416.  
  417.     if (!$meta_id) return false;
  418.  
  419.     if (empty($value)) {
  420.         $wpdb->query("DELETE FROM $wpdb->postmeta WHERE post_id = '$post_id'
  421. AND meta_key = '$key'");
  422.     } else {
  423.         $wpdb->query("DELETE FROM $wpdb->postmeta WHERE post_id = '$post_id'
  424. AND meta_key = '$key' AND meta_value = '$value'");
  425.     }
  426.         
  427.     return true;
  428. }
  429.  
  430. function get_post_meta($post_id, $key, $single = false) {
  431.     global $wpdb, $post_meta_cache;
  432.  
  433.     if (isset($post_meta_cache[$post_id][$key])) {
  434.         if ($single) {
  435.             return $post_meta_cache[$post_id][$key][0];
  436.         } else {
  437.             return $post_meta_cache[$post_id][$key];
  438.         }
  439.     }
  440.  
  441.     $metalist = $wpdb->get_results("SELECT meta_value FROM $wpdb->postmeta WHERE post_id = '$post_id' AND meta_key = '$key'", ARRAY_N);
  442.  
  443.     $values = array();
  444.     if ($metalist) {
  445.         foreach ($metalist as $metarow) {
  446.             $values[] = $metarow[0];
  447.         }
  448.     }
  449.  
  450.     if ($single) {
  451.         if (count($values)) {
  452.             return $values[0];
  453.         } else {
  454.             return '';
  455.         }
  456.     } else {
  457.         return $values;
  458.     }
  459. }
  460.  
  461. function update_post_meta($post_id, $key, $value, $prev_value = '') {
  462.     global $wpdb, $post_meta_cache;
  463.  
  464.         if(! $wpdb->get_var("SELECT meta_key FROM $wpdb->postmeta WHERE meta_key
  465. = '$key' AND post_id = '$post_id'") ) {
  466.             return false;
  467.         }
  468.  
  469.     if (empty($prev_value)) {
  470.         $wpdb->query("UPDATE $wpdb->postmeta SET meta_value = '$value' WHERE
  471. meta_key = '$key' AND post_id = '$post_id'");
  472.     } else {
  473.         $wpdb->query("UPDATE $wpdb->postmeta SET meta_value = '$value' WHERE
  474. meta_key = '$key' AND post_id = '$post_id' AND meta_value = '$prev_value'");
  475.     }
  476.  
  477.     return true;
  478. }
  479.  
  480. // Deprecated.  Use get_post().
  481. function get_postdata($postid) {
  482.     $post = &get_post($postid);
  483.     
  484.     $postdata = array (
  485.         'ID' => $post->ID, 
  486.         'Author_ID' => $post->post_author, 
  487.         'Date' => $post->post_date, 
  488.         'Content' => $post->post_content, 
  489.         'Excerpt' => $post->post_excerpt, 
  490.         'Title' => $post->post_title, 
  491.         'Category' => $post->post_category,
  492.         'post_status' => $post->post_status,
  493.         'comment_status' => $post->comment_status,
  494.         'ping_status' => $post->ping_status,
  495.         'post_password' => $post->post_password,
  496.         'to_ping' => $post->to_ping,
  497.         'pinged' => $post->pinged,
  498.         'post_name' => $post->post_name
  499.     );
  500.  
  501.     return $postdata;
  502. }
  503.  
  504. // Retrieves post data given a post ID or post object. 
  505. // Handles post caching.
  506. function &get_post(&$post, $output = OBJECT) {
  507.     global $post_cache, $wpdb;
  508.  
  509.     if ( empty($post) ) {
  510.         if ( isset($GLOBALS['post']) )
  511.             $post = & $GLOBALS['post'];
  512.         else
  513.             $post = null;
  514.     } elseif (is_object($post) ) {
  515.         if (! isset($post_cache[$post->ID]))
  516.             $post_cache[$post->ID] = &$post;
  517.         $post = & $post_cache[$post->ID];
  518.     } else {
  519.         if (isset($post_cache[$post]))
  520.             $post = & $post_cache[$post];
  521.         else {
  522.             $query = "SELECT * FROM $wpdb->posts WHERE ID=$post";
  523.             $post_cache[$post] = & $wpdb->get_row($query);
  524.             $post = & $post_cache[$post];
  525.         }
  526.     }
  527.  
  528.     if ( $output == OBJECT ) {
  529.         return $post;
  530.     } elseif ( $output == ARRAY_A ) {
  531.         return get_object_vars($post);
  532.     } elseif ( $output == ARRAY_N ) {
  533.         return array_values(get_object_vars($post));
  534.     } else {
  535.         return $post;
  536.     }
  537. }
  538.  
  539. // Retrieves page data given a page ID or page object. 
  540. // Handles page caching.
  541. function &get_page(&$page, $output = OBJECT) {
  542.     global $page_cache, $wpdb;
  543.  
  544.     if ( empty($page) ) {
  545.         if ( isset($GLOBALS['page']) )
  546.             $page = & $GLOBALS['page'];
  547.         else
  548.             $page = null;
  549.     } elseif (is_object($page) ) {
  550.         if (! isset($page_cache[$page->ID]))
  551.             $page_cache[$page->ID] = &$page;
  552.         $page = & $page_cache[$page->ID];
  553.     } else {
  554.         if ( isset($GLOBALS['page']) && ($page == $GLOBALS['page']->ID) )
  555.             $page = & $GLOBALS['page'];
  556.         elseif (isset($page_cache[$page]))
  557.             $page = & $page_cache[$page];
  558.         else {
  559.             $query = "SELECT * FROM $wpdb->posts WHERE ID=$page";
  560.             $page_cache[$page] = & $wpdb->get_row($query);
  561.             $page = & $page_cache[$page];
  562.         }
  563.     }
  564.  
  565.     if ( $output == OBJECT ) {
  566.         return $page;
  567.     } elseif ( $output == ARRAY_A ) {
  568.         return get_object_vars($page);
  569.     } elseif ( $output == ARRAY_N ) {
  570.         return array_values(get_object_vars($page));
  571.     } else {
  572.         return $page;
  573.     }
  574. }
  575.  
  576. // Retrieves category data given a category ID or category object. 
  577. // Handles category caching.
  578. function &get_category(&$category, $output = OBJECT) {
  579.     global $cache_categories, $wpdb;
  580.  
  581.     if ( empty($category) )
  582.         return null;
  583.  
  584.     if ( ! isset($cache_categories))
  585.         update_category_cache();
  586.  
  587.     if (is_object($category)) {
  588.         if ( ! isset($cache_categories[$category->cat_ID]))
  589.             $cache_categories[$category->cat_ID] = &$category;
  590.         $category = & $cache_categories[$category->cat_ID];
  591.     } else {
  592.         if ( !isset($cache_categories[$category]) ) {
  593.             $category = $wpdb->get_row("SELECT * FROM $wpdb->categories WHERE cat_ID = $category");
  594.             $cache_categories[$category->cat_ID] = & $category;
  595.         } else {
  596.             $category = & $cache_categories[$category];
  597.         }
  598.     }
  599.  
  600.     if ( $output == OBJECT ) {
  601.         return $category;
  602.     } elseif ( $output == ARRAY_A ) {
  603.         return get_object_vars($category);
  604.     } elseif ( $output == ARRAY_N ) {
  605.         return array_values(get_object_vars($category));
  606.     } else {
  607.         return $category;
  608.     }
  609. }
  610.  
  611. function get_catname($cat_ID) {
  612.     $category = &get_category($cat_ID);
  613.     return $category->cat_name;
  614. }
  615.  
  616. function gzip_compression() {
  617.     if ( strstr($_SERVER['PHP_SELF'], 'wp-admin') ) return false;
  618.     if ( !get_settings('gzipcompression') ) return false;
  619.  
  620.     if( extension_loaded('zlib') ) {
  621.         ob_start('ob_gzhandler');
  622.     }
  623. }
  624.  
  625.  
  626. // functions to count the page generation time (from phpBB2)
  627. // ( or just any time between timer_start() and timer_stop() )
  628.  
  629. function timer_stop($display = 0, $precision = 3) { //if called like timer_stop(1), will echo $timetotal
  630.     global $timestart, $timeend;
  631.     $mtime = microtime();
  632.     $mtime = explode(' ',$mtime);
  633.     $mtime = $mtime[1] + $mtime[0];
  634.     $timeend = $mtime;
  635.     $timetotal = $timeend-$timestart;
  636.     if ($display)
  637.         echo number_format($timetotal,$precision);
  638.     return $timetotal;
  639. }
  640.  
  641. function weblog_ping($server = '', $path = '') {
  642.     global $wp_version;
  643.     include_once (ABSPATH . WPINC . '/class-IXR.php');
  644.  
  645.     // using a timeout of 3 seconds should be enough to cover slow servers
  646.     $client = new IXR_Client($server, ((!strlen(trim($path)) || ('/' == $path)) ? false : $path));
  647.     $client->timeout = 3;
  648.     $client->useragent .= ' -- WordPress/'.$wp_version;
  649.  
  650.     // when set to true, this outputs debug messages by itself
  651.     $client->debug = false;
  652.     $home = trailingslashit( get_option('home') );
  653.     if ( !$client->query('weblogUpdates.extendedPing', get_settings('blogname'), $home, get_bloginfo('rss2_url') ) ) // then try a normal ping
  654.         $client->query('weblogUpdates.ping', get_settings('blogname'), $home);
  655. }
  656.  
  657. function generic_ping($post_id = 0) {
  658.     $services = get_settings('ping_sites');
  659.     $services = preg_replace("|(\s)+|", '$1', $services); // Kill dupe lines
  660.     $services = trim($services);
  661.     if ('' != $services) {
  662.         $services = explode("\n", $services);
  663.         foreach ($services as $service) {
  664.             weblog_ping($service);
  665.         }
  666.     }
  667.  
  668.     return $post_id;
  669. }
  670.  
  671. // Send a Trackback
  672. function trackback($trackback_url, $title, $excerpt, $ID) {
  673.     global $wpdb, $wp_version;
  674.     $title = urlencode($title);
  675.     $excerpt = urlencode($excerpt);
  676.     $blog_name = urlencode(get_settings('blogname'));
  677.     $tb_url = $trackback_url;
  678.     $url = urlencode(get_permalink($ID));
  679.     $query_string = "title=$title&url=$url&blog_name=$blog_name&excerpt=$excerpt";
  680.     $trackback_url = parse_url($trackback_url);
  681.     $http_request  = 'POST ' . $trackback_url['path'] . ($trackback_url['query'] ? '?'.$trackback_url['query'] : '') . " HTTP/1.0\r\n";
  682.     $http_request .= 'Host: '.$trackback_url['host']."\r\n";
  683.     $http_request .= 'Content-Type: application/x-www-form-urlencoded; charset='.get_settings('blog_charset')."\r\n";
  684.     $http_request .= 'Content-Length: '.strlen($query_string)."\r\n";
  685.     $http_request .= "User-Agent: WordPress/" . $wp_version;
  686.     $http_request .= "\r\n\r\n";
  687.     $http_request .= $query_string;
  688.     if ( '' == $trackback_url['port'] )
  689.         $trackback_url['port'] = 80;
  690.     $fs = @fsockopen($trackback_url['host'], $trackback_url['port'], $errno, $errstr, 4);
  691.     @fputs($fs, $http_request);
  692. /*
  693.     $debug_file = 'trackback.log';
  694.     $fp = fopen($debug_file, 'a');
  695.     fwrite($fp, "\n*****\nRequest:\n\n$http_request\n\nResponse:\n\n");
  696.     while(!@feof($fs)) {
  697.         fwrite($fp, @fgets($fs, 4096));
  698.     }
  699.     fwrite($fp, "\n\n");
  700.     fclose($fp);
  701. */
  702.     @fclose($fs);
  703.  
  704.     $wpdb->query("UPDATE $wpdb->posts SET pinged = CONCAT(pinged, '\n', '$tb_url') WHERE ID = '$ID'");
  705.     $wpdb->query("UPDATE $wpdb->posts SET to_ping = REPLACE(to_ping, '$tb_url', '') WHERE ID = '$ID'");
  706.     return $result;
  707. }
  708.  
  709. function make_url_footnote($content) {
  710.     preg_match_all('/<a(.+?)href=\"(.+?)\"(.*?)>(.+?)<\/a>/', $content, $matches);
  711.     $j = 0;
  712.     for ($i=0; $i<count($matches[0]); $i++) {
  713.         $links_summary = (!$j) ? "\n" : $links_summary;
  714.         $j++;
  715.         $link_match = $matches[0][$i];
  716.         $link_number = '['.($i+1).']';
  717.         $link_url = $matches[2][$i];
  718.         $link_text = $matches[4][$i];
  719.         $content = str_replace($link_match, $link_text.' '.$link_number, $content);
  720.         $link_url = (strtolower(substr($link_url,0,7)) != 'http://') ? get_settings('home') . $link_url : $link_url;
  721.         $links_summary .= "\n".$link_number.' '.$link_url;
  722.     }
  723.     $content = strip_tags($content);
  724.     $content .= $links_summary;
  725.     return $content;
  726. }
  727.  
  728.  
  729. function xmlrpc_getposttitle($content) {
  730.     global $post_default_title;
  731.     if (preg_match('/<title>(.+?)<\/title>/is', $content, $matchtitle)) {
  732.         $post_title = $matchtitle[0];
  733.         $post_title = preg_replace('/<title>/si', '', $post_title);
  734.         $post_title = preg_replace('/<\/title>/si', '', $post_title);
  735.     } else {
  736.         $post_title = $post_default_title;
  737.     }
  738.     return $post_title;
  739. }
  740.     
  741. function xmlrpc_getpostcategory($content) {
  742.     global $post_default_category;
  743.     if (preg_match('/<category>(.+?)<\/category>/is', $content, $matchcat)) {
  744.         $post_category = trim($matchcat[1], ',');
  745.         $post_category = explode(',', $post_category);
  746.     } else {
  747.         $post_category = $post_default_category;
  748.     }
  749.     return $post_category;
  750. }
  751.  
  752. function xmlrpc_removepostdata($content) {
  753.     $content = preg_replace('/<title>(.+?)<\/title>/si', '', $content);
  754.     $content = preg_replace('/<category>(.+?)<\/category>/si', '', $content);
  755.     $content = trim($content);
  756.     return $content;
  757. }
  758.  
  759. function debug_fopen($filename, $mode) {
  760.     global $debug;
  761.     if ($debug == 1) {
  762.         $fp = fopen($filename, $mode);
  763.         return $fp;
  764.     } else {
  765.         return false;
  766.     }
  767. }
  768.  
  769. function debug_fwrite($fp, $string) {
  770.     global $debug;
  771.     if ($debug == 1) {
  772.         fwrite($fp, $string);
  773.     }
  774. }
  775.  
  776. function debug_fclose($fp) {
  777.     global $debug;
  778.     if ($debug == 1) {
  779.         fclose($fp);
  780.     }
  781. }
  782.  
  783. function do_enclose( $content, $post_ID ) {
  784.     global $wp_version, $wpdb;
  785.     include_once (ABSPATH . WPINC . '/class-IXR.php');
  786.  
  787.     $log = debug_fopen(ABSPATH . '/enclosures.log', 'a');
  788.     $post_links = array();
  789.     debug_fwrite($log, 'BEGIN '.date('YmdHis', time())."\n");
  790.  
  791.     $pung = get_enclosed( $post_ID );
  792.  
  793.     $ltrs = '\w';
  794.     $gunk = '/#~:.?+=&%@!\-';
  795.     $punc = '.:?\-';
  796.     $any = $ltrs . $gunk . $punc;
  797.  
  798.     preg_match_all("{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp);
  799.  
  800.     debug_fwrite($log, 'Post contents:');
  801.     debug_fwrite($log, $content."\n");
  802.  
  803.     foreach($post_links_temp[0] as $link_test) :
  804.         if ( !in_array($link_test, $pung) ) : // If we haven't pung it already
  805.             $test = parse_url($link_test);
  806.             if (isset($test['query']))
  807.                 $post_links[] = $link_test;
  808.             elseif(($test['path'] != '/') && ($test['path'] != ''))
  809.                 $post_links[] = $link_test;
  810.         endif;
  811.     endforeach;
  812.  
  813.     foreach ($post_links as $url) :
  814.         if ( $url != '' && !$wpdb->get_var("SELECT post_id FROM $wpdb->postmeta WHERE post_id = '$post_ID' AND meta_key = 'enclosure' AND meta_value LIKE ('$url%')") ) {
  815.             if ( $headers = wp_get_http_headers( $url) ) {
  816.                 $len  = (int) $headers['content-length'];
  817.                 $type = addslashes( $headers['content-type'] );
  818.                 $allowed_types = array( 'video', 'audio' );
  819.                 if( in_array( substr( $type, 0, strpos( $type, "/" ) ), $allowed_types ) ) {
  820.                     $meta_value = "$url\n$len\n$type\n";
  821.                     $wpdb->query( "INSERT INTO `$wpdb->postmeta` ( `post_id` , `meta_key` , `meta_value` )
  822.                     VALUES ( '$post_ID', 'enclosure' , '$meta_value')" );
  823.                 }
  824.             }
  825.         }
  826.     endforeach;
  827. }
  828.  
  829. function wp_get_http_headers( $url ) {
  830.     set_time_limit( 60 ); 
  831.     $parts = parse_url( $url );
  832.     $file  = $parts['path'] . $parts['query'];
  833.     $host  = $parts['host'];
  834.     if ( !isset( $parts['port'] ) )
  835.         $parts['port'] = 80;
  836.  
  837.     $head = "HEAD $file HTTP/1.1\r\nHOST: $host\r\n\r\n";
  838.  
  839.     $fp = @fsockopen($host, $parts['port'], $err_num, $err_msg, 3);
  840.     if ( !$fp )
  841.         return false;
  842.  
  843.     $response = '';
  844.     fputs( $fp, $head );
  845.     while ( !feof( $fp ) && strpos( $response, "\r\n\r\n" ) == false )
  846.         $response .= fgets( $fp, 2048 );
  847.     fclose( $fp );
  848.     preg_match_all('/(.*?): (.*)\r/', $response, $matches);
  849.     $count = count($matches[1]);
  850.     for ( $i = 0; $i < $count; $i++) {
  851.         $key = strtolower($matches[1][$i]);
  852.         $headers["$key"] = $matches[2][$i];
  853.     }
  854.  
  855.     preg_match('/.*([0-9]{3}).*/', $response, $return);
  856.     $headers['response'] = $return[1]; // HTTP response code eg 204, 200, 404
  857.     return $headers;
  858. }
  859.  
  860. // Deprecated.  Use the new post loop.
  861. function start_wp() {
  862.     global $wp_query, $post;
  863.  
  864.     // Since the old style loop is being used, advance the query iterator here.
  865.     $wp_query->next_post();
  866.  
  867.     setup_postdata($post);
  868. }
  869.  
  870. // Setup global post data.
  871. function setup_postdata($post) {
  872.   global $id, $postdata, $authordata, $day, $page, $pages, $multipage, $more, $numpages, $wp_query;
  873.     global $pagenow;
  874.  
  875.     $id = $post->ID;
  876.  
  877.     $authordata = get_userdata($post->post_author);
  878.  
  879.     $day = mysql2date('d.m.y', $post->post_date);
  880.     $currentmonth = mysql2date('m', $post->post_date);
  881.     $numpages = 1;
  882.     $page = get_query_var('page');
  883.     if (!$page)
  884.         $page = 1;
  885.     if (is_single() || is_page())
  886.         $more = 1;
  887.     $content = $post->post_content;
  888.     if (preg_match('/<!--nextpage-->/', $content)) {
  889.         if ($page > 1)
  890.             $more = 1;
  891.         $multipage = 1;
  892.         $content = str_replace("\n<!--nextpage-->\n", '<!--nextpage-->', $content);
  893.         $content = str_replace("\n<!--nextpage-->", '<!--nextpage-->', $content);
  894.         $content = str_replace("<!--nextpage-->\n", '<!--nextpage-->', $content);
  895.         $pages = explode('<!--nextpage-->', $content);
  896.         $numpages = count($pages);
  897.     } else {
  898.         $pages[0] = $post->post_content;
  899.         $multipage = 0;
  900.     }
  901.     return true;
  902. }
  903.  
  904. function is_new_day() {
  905.     global $day, $previousday;
  906.     if ($day != $previousday) {
  907.         return(1);
  908.     } else {
  909.         return(0);
  910.     }
  911. }
  912.  
  913. // Filters: these are the core of WP's plugin architecture
  914.  
  915. function merge_filters($tag) {
  916.     global $wp_filter;
  917.     if (isset($wp_filter['all'])) {
  918.         foreach ($wp_filter['all'] as $priority => $functions) {
  919.             if (isset($wp_filter[$tag][$priority]))
  920.                 $wp_filter[$tag][$priority] = array_merge($wp_filter['all'][$priority], $wp_filter[$tag][$priority]);
  921.             else
  922.                 $wp_filter[$tag][$priority] = array_merge($wp_filter['all'][$priority], array());
  923.             $wp_filter[$tag][$priority] = array_unique($wp_filter[$tag][$priority]);
  924.         }
  925.     }
  926.  
  927.     if ( isset($wp_filter[$tag]) )
  928.         ksort( $wp_filter[$tag] );
  929. }
  930.  
  931. function apply_filters($tag, $string) {
  932.     global $wp_filter;
  933.     
  934.     $args = array_slice(func_get_args(), 2);
  935.  
  936.     merge_filters($tag);
  937.     
  938.     if (!isset($wp_filter[$tag])) {
  939.         return $string;
  940.     }
  941.     foreach ($wp_filter[$tag] as $priority => $functions) {
  942.         if (!is_null($functions)) {
  943.             foreach($functions as $function) {
  944.  
  945.                 $all_args = array_merge(array($string), $args);
  946.                 $function_name = $function['function'];
  947.                 $accepted_args = $function['accepted_args'];
  948.  
  949.                 if($accepted_args == 1) {
  950.                     $the_args = array($string);
  951.                 } elseif ($accepted_args > 1) {
  952.                     $the_args = array_slice($all_args, 0, $accepted_args);
  953.                 } elseif($accepted_args == 0) {
  954.                     $the_args = NULL;
  955.                 } else {
  956.                     $the_args = $all_args;
  957.                 }
  958.  
  959.                 $string = call_user_func_array($function_name, $the_args);
  960.             }
  961.         }
  962.     }
  963.     return $string;
  964. }
  965.  
  966. function add_filter($tag, $function_to_add, $priority = 10, $accepted_args = 1) {
  967.     global $wp_filter;
  968.  
  969.     // check that we don't already have the same filter at the same priority
  970.     if (isset($wp_filter[$tag]["$priority"])) {
  971.         foreach($wp_filter[$tag]["$priority"] as $filter) {
  972.             // uncomment if we want to match function AND accepted_args
  973.             //if ($filter == array($function, $accepted_args)) {
  974.             if ($filter['function'] == $function_to_add) {
  975.                 return true;
  976.             }
  977.         }
  978.     }
  979.  
  980.     // So the format is wp_filter['tag']['array of priorities']['array of ['array (functions, accepted_args)]']
  981.     $wp_filter[$tag]["$priority"][] = array('function'=>$function_to_add, 'accepted_args'=>$accepted_args);
  982.     return true;
  983. }
  984.  
  985. function remove_filter($tag, $function_to_remove, $priority = 10, $accepted_args = 1) {
  986.     global $wp_filter;
  987.  
  988.     // rebuild the list of filters
  989.     if (isset($wp_filter[$tag]["$priority"])) {
  990.         foreach($wp_filter[$tag]["$priority"] as $filter) {
  991.             if ($filter['function'] != $function_to_remove) {
  992.                 $new_function_list[] = $filter;
  993.             }
  994.         }
  995.         $wp_filter[$tag]["$priority"] = $new_function_list;
  996.     }
  997.     return true;
  998. }
  999.  
  1000. // The *_action functions are just aliases for the *_filter functions, they take special strings instead of generic content
  1001.  
  1002. function do_action($tag, $arg = '') {
  1003.     global $wp_filter;
  1004.     $extra_args = array_slice(func_get_args(), 2);
  1005.      if ( is_array($arg) )
  1006.          $args = array_merge($arg, $extra_args);
  1007.     else
  1008.         $args = array_merge(array($arg), $extra_args);
  1009.     
  1010.     merge_filters($tag);
  1011.     
  1012.     if (!isset($wp_filter[$tag])) {
  1013.         return;
  1014.     }
  1015.     foreach ($wp_filter[$tag] as $priority => $functions) {
  1016.         if (!is_null($functions)) {
  1017.             foreach($functions as $function) {
  1018.  
  1019.                 $function_name = $function['function'];
  1020.                 $accepted_args = $function['accepted_args'];
  1021.  
  1022.                 if($accepted_args == 1) {
  1023.                     if ( is_array($arg) )
  1024.                         $the_args = $arg;
  1025.                     else
  1026.                         $the_args = array($arg);
  1027.                 } elseif ($accepted_args > 1) {
  1028.                     $the_args = array_slice($args, 0, $accepted_args);
  1029.                 } elseif($accepted_args == 0) {
  1030.                     $the_args = NULL;
  1031.                 } else {
  1032.                     $the_args = $args;
  1033.                 }
  1034.  
  1035.                 $string = call_user_func_array($function_name, $the_args);
  1036.             }
  1037.         }
  1038.     }
  1039. }
  1040.  
  1041. function add_action($tag, $function_to_add, $priority = 10, $accepted_args = 1) {
  1042.     add_filter($tag, $function_to_add, $priority, $accepted_args);
  1043. }
  1044.  
  1045. function remove_action($tag, $function_to_remove, $priority = 10, $accepted_args = 1) {
  1046.     remove_filter($tag, $function_to_remove, $priority, $accepted_args);
  1047. }
  1048.  
  1049. function get_page_uri($page_id) {
  1050.     $page = get_page($page_id);
  1051.     $uri = urldecode($page->post_name);
  1052.  
  1053.     // A page cannot be it's own parent.
  1054.     if ($page->post_parent == $page->ID) {
  1055.         return $uri;
  1056.     }
  1057.     
  1058.     while ($page->post_parent != 0) {
  1059.         $page = get_page($page->post_parent);
  1060.         $uri = urldecode($page->post_name) . "/" . $uri;
  1061.     }
  1062.  
  1063.     return $uri;
  1064. }
  1065.  
  1066. function get_posts($args) {
  1067.     global $wpdb;
  1068.     parse_str($args, $r);
  1069.     if (!isset($r['numberposts'])) $r['numberposts'] = 5;
  1070.     if (!isset($r['offset'])) $r['offset'] = 0;
  1071.     if (!isset($r['category'])) $r['category'] = '';
  1072.     if (!isset($r['orderby'])) $r['orderby'] = 'post_date';
  1073.     if (!isset($r['order'])) $r['order'] = 'DESC';
  1074.  
  1075.     $now = current_time('mysql');
  1076.  
  1077.     $posts = $wpdb->get_results(
  1078.         "SELECT DISTINCT * FROM $wpdb->posts " .
  1079.         ( empty( $r['category'] ) ? "" : ", $wpdb->post2cat " ) .
  1080.         " WHERE post_date <= '$now' AND (post_status = 'publish') ".
  1081.         ( empty( $r['category'] ) ? "" : "AND $wpdb->posts.ID = $wpdb->post2cat.post_id AND $wpdb->post2cat.category_id = " . $r['category']. " " ) .
  1082.         " GROUP BY $wpdb->posts.ID ORDER BY " . $r['orderby'] . " " . $r['order'] . "  LIMIT " . $r['offset'] . ',' . $r['numberposts'] );
  1083.     
  1084.     update_post_caches($posts);
  1085.     
  1086.     return $posts;
  1087. }
  1088.  
  1089. function &query_posts($query) {
  1090.     global $wp_query;
  1091.     return $wp_query->query($query);
  1092. }
  1093.  
  1094. function update_post_cache(&$posts) {
  1095.     global $post_cache;
  1096.  
  1097.     if ( !$posts )
  1098.         return;
  1099.  
  1100.     for ($i = 0; $i < count($posts); $i++) {
  1101.         $post_cache[$posts[$i]->ID] = &$posts[$i];
  1102.     }
  1103. }
  1104.  
  1105. function update_page_cache(&$pages) {
  1106.     global $page_cache;
  1107.  
  1108.     if ( !$pages )
  1109.         return;
  1110.  
  1111.     for ($i = 0; $i < count($pages); $i++) {
  1112.         $page_cache[$pages[$i]->ID] = &$pages[$i];
  1113.     }
  1114. }
  1115.  
  1116. function update_post_category_cache($post_ids) {
  1117.     global $wpdb, $category_cache, $cache_categories;
  1118.  
  1119.     if (empty($post_ids))
  1120.         return;
  1121.  
  1122.     if (is_array($post_ids))
  1123.         $post_ids = implode(',', $post_ids);
  1124.  
  1125.     $dogs = $wpdb->get_results("SELECT DISTINCT
  1126.     post_id, cat_ID FROM $wpdb->categories, $wpdb->post2cat
  1127.     WHERE category_id = cat_ID AND post_id IN ($post_ids)");
  1128.  
  1129.     if (! isset($cache_categories))
  1130.         update_category_cache();
  1131.         
  1132.     if ( !empty($dogs) ) {
  1133.         foreach ($dogs as $catt) {
  1134.             $category_cache[$catt->post_id][$catt->cat_ID] = &$cache_categories[$catt->cat_ID];
  1135.         }
  1136.     }
  1137. }
  1138.  
  1139. function update_post_caches(&$posts) {
  1140.     global $post_cache, $category_cache, $comment_count_cache, $post_meta_cache;
  1141.     global $wpdb;
  1142.     
  1143.     // No point in doing all this work if we didn't match any posts.
  1144.     if ( !$posts )
  1145.         return;
  1146.  
  1147.     // Get the categories for all the posts
  1148.     for ($i = 0; $i < count($posts); $i++) {
  1149.         $post_id_list[] = $posts[$i]->ID;
  1150.         $post_cache[$posts[$i]->ID] = &$posts[$i];
  1151.     }
  1152.  
  1153.     $post_id_list = implode(',', $post_id_list);
  1154.     
  1155.     update_post_category_cache($post_id_list);
  1156.  
  1157.     // Do the same for comment numbers
  1158.     $comment_counts = $wpdb->get_results("SELECT ID, COUNT( comment_ID ) AS ccount
  1159.     FROM $wpdb->posts
  1160.     LEFT JOIN $wpdb->comments ON ( comment_post_ID = ID  AND comment_approved =  '1')
  1161.     WHERE ID IN ($post_id_list)
  1162.     GROUP BY ID");
  1163.     
  1164.     if ($comment_counts) {
  1165.         foreach ($comment_counts as $comment_count)
  1166.             $comment_count_cache["$comment_count->ID"] = $comment_count->ccount;
  1167.     }
  1168.  
  1169.     // Get post-meta info
  1170.     if ( $meta_list = $wpdb->get_results("SELECT post_id, meta_key, meta_value FROM $wpdb->postmeta  WHERE post_id IN($post_id_list) ORDER BY post_id, meta_key", ARRAY_A) ) {
  1171.         // Change from flat structure to hierarchical:
  1172.         $post_meta_cache = array();
  1173.         foreach ($meta_list as $metarow) {
  1174.             $mpid = $metarow['post_id'];
  1175.             $mkey = $metarow['meta_key'];
  1176.             $mval = $metarow['meta_value'];
  1177.  
  1178.             // Force subkeys to be array type:
  1179.             if (!isset($post_meta_cache[$mpid]) || !is_array($post_meta_cache[$mpid]))
  1180.                 $post_meta_cache[$mpid] = array();
  1181.             if (!isset($post_meta_cache[$mpid]["$mkey"]) || !is_array($post_meta_cache[$mpid]["$mkey"]))
  1182.                 $post_meta_cache[$mpid]["$mkey"] = array();
  1183.  
  1184.             // Add a value to the current pid/key:
  1185.             $post_meta_cache[$mpid][$mkey][] = $mval;
  1186.         }
  1187.     }
  1188. }
  1189.  
  1190. function update_category_cache() {
  1191.     global $cache_categories, $wpdb;
  1192.     $dogs = $wpdb->get_results("SELECT * FROM $wpdb->categories");
  1193.     foreach ($dogs as $catt)
  1194.         $cache_categories[$catt->cat_ID] = $catt;
  1195. }
  1196.  
  1197. function update_user_cache() {
  1198.     global $cache_userdata, $wpdb;
  1199.     
  1200.     if ( $users = $wpdb->get_results("SELECT * FROM $wpdb->users WHERE user_level > 0") ) :
  1201.         foreach ($users as $user) :
  1202.             $cache_userdata[$user->ID] = $user;
  1203.             $cache_userdata[$user->user_login] =& $cache_userdata[$user->ID];
  1204.         endforeach;
  1205.         return true;
  1206.     else : 
  1207.         return false;
  1208.     endif;
  1209. }
  1210.  
  1211. function wp_head() {
  1212.     do_action('wp_head');
  1213. }
  1214.  
  1215. function wp_footer() {
  1216.     do_action('wp_footer');
  1217. }
  1218.  
  1219. function is_single ($post = '') {
  1220.     global $wp_query;
  1221.  
  1222.     if ( !$wp_query->is_single )
  1223.         return false;
  1224.  
  1225.     if ( empty( $post) )
  1226.         return true;
  1227.  
  1228.     $post_obj = $wp_query->get_queried_object();
  1229.  
  1230.     if ( $post == $post_obj->ID ) 
  1231.         return true;
  1232.     elseif ( $post == $post_obj->post_title ) 
  1233.         return true;
  1234.     elseif ( $post == $post_obj->post_name )
  1235.         return true;
  1236.  
  1237.     return false;
  1238. }
  1239.  
  1240. function is_page ($page = '') {
  1241.     global $wp_query;
  1242.  
  1243.     if (! $wp_query->is_page) {
  1244.         return false;
  1245.     }
  1246.  
  1247.     if (empty($page)) {
  1248.         return true;
  1249.     }
  1250.  
  1251.     $page_obj = $wp_query->get_queried_object();
  1252.         
  1253.     if ($page == $page_obj->ID) {
  1254.         return true;
  1255.     } else if ($page == $page_obj->post_title) {
  1256.         return true;
  1257.     } else if ($page == $page_obj->post_name) {
  1258.         return true;
  1259.     }
  1260.  
  1261.     return false;
  1262. }
  1263.  
  1264. function is_archive () {
  1265.     global $wp_query;
  1266.  
  1267.     return $wp_query->is_archive;
  1268. }
  1269.  
  1270. function is_date () {
  1271.     global $wp_query;
  1272.  
  1273.     return $wp_query->is_date;
  1274. }
  1275.  
  1276. function is_year () {
  1277.     global $wp_query;
  1278.  
  1279.     return $wp_query->is_year;
  1280. }
  1281.  
  1282. function is_month () {
  1283.     global $wp_query;
  1284.  
  1285.     return $wp_query->is_month;
  1286. }
  1287.  
  1288. function is_day () {
  1289.     global $wp_query;
  1290.  
  1291.     return $wp_query->is_day;
  1292. }
  1293.  
  1294. function is_time () {
  1295.     global $wp_query;
  1296.  
  1297.     return $wp_query->is_time;
  1298. }
  1299.  
  1300. function is_author ($author = '') {
  1301.     global $wp_query;
  1302.  
  1303.     if (! $wp_query->is_author) {
  1304.         return false;
  1305.     }
  1306.  
  1307.     if (empty($author)) {
  1308.         return true;
  1309.     }
  1310.  
  1311.     $author_obj = $wp_query->get_queried_object();
  1312.         
  1313.     if ($author == $author_obj->ID) {
  1314.         return true;
  1315.     } else if ($author == $author_obj->user_nickname) {
  1316.         return true;
  1317.     } else if ($author == $author_obj->user_nicename) {
  1318.         return true;
  1319.     }
  1320.  
  1321.     return false;
  1322. }
  1323.  
  1324. function is_category ($category = '') {
  1325.     global $wp_query;
  1326.  
  1327.     if (! $wp_query->is_category) {
  1328.         return false;
  1329.     }
  1330.  
  1331.     if (empty($category)) {
  1332.         return true;
  1333.     }
  1334.  
  1335.     $cat_obj = $wp_query->get_queried_object();
  1336.         
  1337.     if ($category == $cat_obj->cat_ID) {
  1338.         return true;
  1339.     } else if ($category == $cat_obj->cat_name) {
  1340.         return true;
  1341.     } else if ($category == $cat_obj->category_nicename) {
  1342.         return true;
  1343.     }
  1344.  
  1345.     return false;
  1346. }
  1347.  
  1348. function is_search () {
  1349.     global $wp_query;
  1350.  
  1351.     return $wp_query->is_search;
  1352. }
  1353.  
  1354. function is_feed () {
  1355.     global $wp_query;
  1356.  
  1357.     return $wp_query->is_feed;
  1358. }
  1359.  
  1360. function is_trackback () {
  1361.     global $wp_query;
  1362.  
  1363.     return $wp_query->is_trackback;
  1364. }
  1365.  
  1366. function is_admin () {
  1367.     global $wp_query;
  1368.  
  1369.     return $wp_query->is_admin;
  1370. }
  1371.  
  1372. function is_home () {
  1373.     global $wp_query;
  1374.  
  1375.     return $wp_query->is_home;
  1376. }
  1377.  
  1378. function is_404 () {
  1379.     global $wp_query;
  1380.  
  1381.     return $wp_query->is_404;
  1382. }
  1383.  
  1384. function is_comments_popup () {
  1385.     global $wp_query;
  1386.  
  1387.     return $wp_query->is_comments_popup;
  1388. }
  1389.  
  1390. function is_paged () {
  1391.     global $wp_query;
  1392.  
  1393.     return $wp_query->is_paged;
  1394. }
  1395.  
  1396. function get_query_var($var) {
  1397.   global $wp_query;
  1398.  
  1399.   return $wp_query->get($var);
  1400. }
  1401.  
  1402. function have_posts() {
  1403.     global $wp_query;
  1404.  
  1405.     return $wp_query->have_posts();
  1406. }
  1407.  
  1408. function rewind_posts() {
  1409.     global $wp_query;
  1410.  
  1411.     return $wp_query->rewind_posts();
  1412. }
  1413.  
  1414. function the_post() {
  1415.     global $wp_query;
  1416.     $wp_query->the_post();
  1417. }
  1418.  
  1419. function get_theme_root() {
  1420.     return apply_filters('theme_root', ABSPATH . "wp-content/themes");
  1421. }
  1422.  
  1423. function get_theme_root_uri() {
  1424.     return apply_filters('theme_root_uri', get_settings('siteurl') . "/wp-content/themes", get_settings('siteurl'));
  1425. }
  1426.  
  1427. function get_stylesheet() {
  1428.     return apply_filters('stylesheet', get_settings('stylesheet'));
  1429. }
  1430.  
  1431. function get_stylesheet_directory() {
  1432.     $stylesheet = get_stylesheet();
  1433.     $stylesheet_dir = get_theme_root() . "/$stylesheet";
  1434.     return apply_filters('stylesheet_directory', $stylesheet_dir, $stylesheet);
  1435. }
  1436.  
  1437. function get_stylesheet_directory_uri() {
  1438.     $stylesheet = get_stylesheet();
  1439.     $stylesheet_dir_uri = get_theme_root_uri() . "/$stylesheet";
  1440.     return apply_filters('stylesheet_directory_uri', $stylesheet_dir_uri, $stylesheet);
  1441. }
  1442.  
  1443. function get_stylesheet_uri() {
  1444.     $stylesheet_dir_uri = get_stylesheet_directory_uri();
  1445.     $stylesheet_uri = $stylesheet_dir_uri . "/style.css";
  1446.     return apply_filters('stylesheet_uri', $stylesheet_uri, $stylesheet_dir_uri);
  1447. }
  1448.  
  1449. function get_template() {
  1450.     return apply_filters('template', get_settings('template'));
  1451. }
  1452.  
  1453. function get_template_directory() {
  1454.     $template = get_template();
  1455.     $template_dir = get_theme_root() . "/$template";
  1456.     return apply_filters('template_directory', $template_dir, $template);
  1457. }
  1458.  
  1459. function get_template_directory_uri() {
  1460.     $template = get_template();
  1461.     $template_dir_uri = get_theme_root_uri() . "/$template";
  1462.     return apply_filters('template_directory_uri', $template_dir_uri, $template);
  1463. }
  1464.  
  1465. function get_theme_data($theme_file) {
  1466.     $theme_data = implode('', file($theme_file));
  1467.     preg_match("|Theme Name:(.*)|i", $theme_data, $theme_name);
  1468.     preg_match("|Theme URI:(.*)|i", $theme_data, $theme_uri);
  1469.     preg_match("|Description:(.*)|i", $theme_data, $description);
  1470.     preg_match("|Author:(.*)|i", $theme_data, $author_name);
  1471.     preg_match("|Author URI:(.*)|i", $theme_data, $author_uri);
  1472.     preg_match("|Template:(.*)|i", $theme_data, $template);
  1473.     if ( preg_match("|Version:(.*)|i", $theme_data, $version) )
  1474.         $version = $version[1];
  1475.     else
  1476.         $version ='';
  1477.     if ( preg_match("|Status:(.*)|i", $theme_data, $status) )
  1478.         $status = $status[1];
  1479.     else
  1480.         $status ='publish';
  1481.  
  1482.     $description = wptexturize($description[1]);
  1483.  
  1484.     $name = $theme_name[1];
  1485.     $name = trim($name);
  1486.     $theme = $name;
  1487.     if ('' != $theme_uri[1] && '' != $name) {
  1488.         $theme = '<a href="' . $theme_uri[1] . '" title="' . __('Visit theme homepage') . '">' . $theme . '</a>';
  1489.     }
  1490.  
  1491.     if ('' == $author_uri[1]) {
  1492.         $author = $author_name[1];
  1493.     } else {
  1494.         $author = '<a href="' . $author_uri[1] . '" title="' . __('Visit author homepage') . '">' . $author_name[1] . '</a>';
  1495.     }
  1496.  
  1497.     return array('Name' => $name, 'Title' => $theme, 'Description' => $description, 'Author' => $author, 'Version' => $version, 'Template' => $template[1], 'Status' => $status);
  1498. }
  1499.  
  1500. function get_themes() {
  1501.     global $wp_themes;
  1502.     global $wp_broken_themes;
  1503.  
  1504.     if (isset($wp_themes)) {
  1505.         return $wp_themes;
  1506.     }
  1507.  
  1508.     $themes = array();
  1509.     $wp_broken_themes = array();
  1510.     $theme_root = get_theme_root();
  1511.     $theme_loc = str_replace(ABSPATH, '', $theme_root);
  1512.  
  1513.     // Files in wp-content/themes directory
  1514.     $themes_dir = @ dir($theme_root);
  1515.     if ($themes_dir) {
  1516.         while(($theme_dir = $themes_dir->read()) !== false) {
  1517.             if (is_dir($theme_root . '/' . $theme_dir)) {
  1518.                 if ($theme_dir{0} == '.' || $theme_dir == '..' || $theme_dir == 'CVS') {
  1519.                     continue;
  1520.                 }
  1521.                 $stylish_dir = @ dir($theme_root . '/' . $theme_dir);
  1522.                 $found_stylesheet = false;
  1523.                 while(($theme_file = $stylish_dir->read()) !== false) {
  1524.                     if ( $theme_file == 'style.css' ) {
  1525.                         $theme_files[] = $theme_dir . '/' . $theme_file;
  1526.                         $found_stylesheet = true;
  1527.                         break;
  1528.                     }
  1529.                 }
  1530.                 if (!$found_stylesheet) {
  1531.                     $wp_broken_themes[$theme_dir] = array('Name' => $theme_dir, 'Title' => $theme_dir, 'Description' => __('Stylesheet is missing.'));
  1532.                 }
  1533.             }
  1534.         }
  1535.     }
  1536.  
  1537.     if (!$themes_dir || !$theme_files) {
  1538.         return $themes;
  1539.     }
  1540.  
  1541.     sort($theme_files);
  1542.  
  1543.     foreach($theme_files as $theme_file) {
  1544.         $theme_data = get_theme_data("$theme_root/$theme_file");
  1545.       
  1546.         $name = $theme_data['Name']; 
  1547.         $title = $theme_data['Title'];
  1548.         $description = wptexturize($theme_data['Description']);
  1549.         $version = $theme_data['Version'];
  1550.         $author = $theme_data['Author'];
  1551.         $template = $theme_data['Template'];
  1552.         $stylesheet = dirname($theme_file);
  1553.  
  1554.         if (empty($name)) {
  1555.             $name = dirname($theme_file);
  1556.             $title = $name;
  1557.         }
  1558.  
  1559.         if (empty($template)) {
  1560.             if (file_exists(dirname("$theme_root/$theme_file/index.php"))) {
  1561.                 $template = dirname($theme_file);
  1562.             } else {
  1563.                 continue;
  1564.             }
  1565.         }
  1566.  
  1567.         $template = trim($template);
  1568.  
  1569.         if (! file_exists("$theme_root/$template/index.php")) {
  1570.             $wp_broken_themes[$name] = array('Name' => $name, 'Title' => $title, 'Description' => __('Template is missing.'));
  1571.             continue;
  1572.         }
  1573.         
  1574.         $stylesheet_files = array();
  1575.         $stylesheet_dir = @ dir("$theme_root/$stylesheet");
  1576.         if ($stylesheet_dir) {
  1577.             while(($file = $stylesheet_dir->read()) !== false) {
  1578.                 if ( !preg_match('|^\.+$|', $file) && preg_match('|\.css$|', $file) ) 
  1579.                     $stylesheet_files[] = "$theme_loc/$stylesheet/$file";
  1580.             }
  1581.         }
  1582.  
  1583.         $template_files = array();        
  1584.         $template_dir = @ dir("$theme_root/$template");
  1585.         if ($template_dir) {
  1586.             while(($file = $template_dir->read()) !== false) {
  1587.                 if ( !preg_match('|^\.+$|', $file) && preg_match('|\.php$|', $file) ) 
  1588.                     $template_files[] = "$theme_loc/$template/$file";
  1589.             }
  1590.         }
  1591.  
  1592.         $template_dir = dirname($template_files[0]);
  1593.         $stylesheet_dir = dirname($stylesheet_files[0]);
  1594.  
  1595.         if (empty($template_dir)) $template_dir = '/';
  1596.         if (empty($stylesheet_dir)) $stylesheet_dir = '/';
  1597.  
  1598.         // Check for theme name collision.  This occurs if a theme is copied to
  1599.         // a new theme directory and the theme header is not updated.  Whichever
  1600.         // theme is first keeps the name.  Subsequent themes get a suffix applied.
  1601.         // The Default and Classic themes always trump their pretenders.
  1602.         if ( isset($themes[$name]) ) {
  1603.             if ( ('WordPress Default' == $name || 'WordPress Classic' == $name) &&
  1604.                      ('default' == $stylesheet || 'classic' == $stylesheet) ) {
  1605.                 // If another theme has claimed to be one of our default themes, move
  1606.                 // them aside.
  1607.                 $suffix = $themes[$name]['Stylesheet'];
  1608.                 $new_name = "$name/$suffix";
  1609.                 $themes[$new_name] = $themes[$name];
  1610.                 $themes[$new_name]['Name'] = $new_name;
  1611.             } else {
  1612.                 $name = "$name/$stylesheet";
  1613.             }
  1614.         }
  1615.         
  1616.         $themes[$name] = array('Name' => $name, 'Title' => $title, 'Description' => $description, 'Author' => $author, 'Version' => $version, 'Template' => $template, 'Stylesheet' => $stylesheet, 'Template Files' => $template_files, 'Stylesheet Files' => $stylesheet_files, 'Template Dir' => $template_dir, 'Stylesheet Dir' => $stylesheet_dir, 'Status' => $theme_data['Status']);
  1617.     }
  1618.  
  1619.     // Resolve theme dependencies.
  1620.     $theme_names = array_keys($themes);
  1621.  
  1622.     foreach ($theme_names as $theme_name) {
  1623.         $themes[$theme_name]['Parent Theme'] = '';
  1624.         if ($themes[$theme_name]['Stylesheet'] != $themes[$theme_name]['Template']) {
  1625.             foreach ($theme_names as $parent_theme_name) {
  1626.                 if (($themes[$parent_theme_name]['Stylesheet'] == $themes[$parent_theme_name]['Template']) && ($themes[$parent_theme_name]['Template'] == $themes[$theme_name]['Template'])) {
  1627.                     $themes[$theme_name]['Parent Theme'] = $themes[$parent_theme_name]['Name'];
  1628.                     break;
  1629.                 }
  1630.             }
  1631.         }
  1632.     }
  1633.  
  1634.     $wp_themes = $themes;
  1635.  
  1636.     return $themes;
  1637. }
  1638.  
  1639. function get_theme($theme) {
  1640.     $themes = get_themes();
  1641.  
  1642.     if (array_key_exists($theme, $themes)) {
  1643.         return $themes[$theme];
  1644.     }
  1645.  
  1646.     return NULL;
  1647. }
  1648.  
  1649. function get_current_theme() {
  1650.     $themes = get_themes();
  1651.     $theme_names = array_keys($themes);
  1652.     $current_template = get_settings('template');
  1653.     $current_stylesheet = get_settings('stylesheet');
  1654.     $current_theme = 'WordPress Default';
  1655.  
  1656.     if ($themes) {
  1657.         foreach ($theme_names as $theme_name) {
  1658.             if ($themes[$theme_name]['Stylesheet'] == $current_stylesheet &&
  1659.                     $themes[$theme_name]['Template'] == $current_template) {
  1660.                 $current_theme = $themes[$theme_name]['Name'];
  1661.                 break;
  1662.             }
  1663.         }
  1664.     }
  1665.  
  1666.     return $current_theme;
  1667. }
  1668.  
  1669. function get_query_template($type) {
  1670.     $template = '';
  1671.     if ( file_exists(TEMPLATEPATH . "/{$type}.php") )
  1672.         $template = TEMPLATEPATH . "/{$type}.php";
  1673.  
  1674.     return apply_filters("{$type}_template", $template);
  1675. }
  1676.  
  1677. function get_404_template() {
  1678.     return get_query_template('404');
  1679. }
  1680.  
  1681. function get_archive_template() {
  1682.     return get_query_template('archive');
  1683. }
  1684.  
  1685. function get_author_template() {
  1686.     return get_query_template('author');
  1687. }
  1688.  
  1689. function get_category_template() {
  1690.     $template = '';
  1691.     if ( file_exists(TEMPLATEPATH . "/category-" . get_query_var('cat') . '.php') )
  1692.         $template = TEMPLATEPATH . "/category-" . get_query_var('cat') . '.php';
  1693.     else if ( file_exists(TEMPLATEPATH . "/category.php") )
  1694.         $template = TEMPLATEPATH . "/category.php";
  1695.  
  1696.     return apply_filters('category_template', $template);
  1697. }
  1698.  
  1699. function get_date_template() {
  1700.     return get_query_template('date');
  1701. }
  1702.  
  1703. function get_home_template() {
  1704.     $template = '';
  1705.  
  1706.     if ( file_exists(TEMPLATEPATH . "/home.php") )
  1707.         $template = TEMPLATEPATH . "/home.php";
  1708.     else if ( file_exists(TEMPLATEPATH . "/index.php") )
  1709.         $template = TEMPLATEPATH . "/index.php";
  1710.  
  1711.     return apply_filters('home_template', $template);
  1712. }
  1713.  
  1714. function get_page_template() {
  1715.     global $wp_query;
  1716.  
  1717.     $id = $wp_query->post->ID;    
  1718.     $template = get_post_meta($id, '_wp_page_template', true);
  1719.  
  1720.     if ( 'default' == $template )
  1721.         $template = '';
  1722.  
  1723.     if ( ! empty($template) && file_exists(TEMPLATEPATH . "/$template") )
  1724.         $template = TEMPLATEPATH . "/$template";
  1725.     else if ( file_exists(TEMPLATEPATH .  "/page.php") )
  1726.         $template = TEMPLATEPATH .  "/page.php";
  1727.     else
  1728.         $template = '';
  1729.  
  1730.     return apply_filters('page_template', $template);
  1731. }
  1732.  
  1733. function get_paged_template() {
  1734.     return get_query_template('paged');
  1735. }
  1736.  
  1737. function get_search_template() {
  1738.     return get_query_template('search');
  1739. }
  1740.  
  1741. function get_single_template() {
  1742.     return get_query_template('single');
  1743. }
  1744.  
  1745. function get_comments_popup_template() {
  1746.     if ( file_exists( TEMPLATEPATH . '/comments-popup.php') )
  1747.         $template = TEMPLATEPATH . '/comments-popup.php';
  1748.     else
  1749.         $template = get_theme_root() . '/default/comments-popup.php';
  1750.  
  1751.     return apply_filters('comments_popup_template', $template);
  1752. }
  1753.  
  1754. // Borrowed from the PHP Manual user notes. Convert entities, while
  1755. // preserving already-encoded entities:
  1756. function htmlentities2($myHTML) {
  1757.     $translation_table=get_html_translation_table (HTML_ENTITIES,ENT_QUOTES);
  1758.     $translation_table[chr(38)] = '&';
  1759.     return preg_replace("/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/","&" , strtr($myHTML, $translation_table));
  1760. }
  1761.  
  1762.  
  1763. function is_plugin_page() {
  1764.     global $plugin_page;
  1765.  
  1766.     if (isset($plugin_page)) {
  1767.         return true;
  1768.     }
  1769.  
  1770.     return false;
  1771. }
  1772.  
  1773. /*
  1774. add_query_arg: Returns a modified querystring by adding
  1775. a single key & value or an associative array.
  1776. Setting a key value to emptystring removes the key.
  1777. Omitting oldquery_or_uri uses the $_SERVER value.
  1778.  
  1779. Parameters:
  1780. add_query_arg(newkey, newvalue, oldquery_or_uri) or
  1781. add_query_arg(associative_array, oldquery_or_uri)
  1782. */
  1783. function add_query_arg() {
  1784.     $ret = '';
  1785.     if(is_array(func_get_arg(0))) {
  1786.         $uri = @func_get_arg(1);
  1787.     }
  1788.     else {
  1789.         if (@func_num_args() < 3) {
  1790.             $uri = $_SERVER['REQUEST_URI'];
  1791.         } else {
  1792.             $uri = @func_get_arg(2);
  1793.         }
  1794.     }
  1795.  
  1796.     if (strstr($uri, '?')) {
  1797.         $parts = explode('?', $uri, 2);
  1798.         if (1 == count($parts)) {
  1799.             $base = '?';
  1800.             $query = $parts[0];
  1801.         }
  1802.         else {
  1803.             $base = $parts[0] . '?';
  1804.             $query = $parts[1];
  1805.         }
  1806.     }
  1807.     else if (strstr($uri, '/')) {
  1808.         $base = $uri . '?';
  1809.         $query = '';
  1810.     } else {
  1811.         $base = '';
  1812.         $query = $uri;
  1813.     }
  1814.  
  1815.     parse_str($query, $qs);
  1816.     if (is_array(func_get_arg(0))) {
  1817.         $kayvees = func_get_arg(0);
  1818.         $qs = array_merge($qs, $kayvees);
  1819.     }
  1820.     else
  1821.     {
  1822.             $qs[func_get_arg(0)] = func_get_arg(1);
  1823.     }
  1824.  
  1825.     foreach($qs as $k => $v)
  1826.     {
  1827.             if($v != '')
  1828.         {
  1829.                     if($ret != '') $ret .= '&';
  1830.                     $ret .= "$k=$v";
  1831.         }
  1832.     }
  1833.     $ret = $base . $ret;   
  1834.     return trim($ret, '?');
  1835. }
  1836.  
  1837. function remove_query_arg($key, $query) {
  1838.     add_query_arg($key, '', $query);
  1839. }
  1840.  
  1841. function load_template($file) {
  1842.     global $posts, $post, $wp_did_header, $wp_did_template_redirect, $wp_query,
  1843.         $wp_rewrite, $wpdb;
  1844.  
  1845.     extract($wp_query->query_vars);
  1846.  
  1847.     require_once($file);
  1848. }
  1849.  
  1850. function add_magic_quotes($array) {
  1851.     foreach ($array as $k => $v) {
  1852.         if (is_array($v)) {
  1853.             $array[$k] = add_magic_quotes($v);
  1854.         } else {
  1855.             $array[$k] = addslashes($v);
  1856.         }
  1857.     }
  1858.     return $array;
  1859. }
  1860.  
  1861. function wp_remote_fopen( $uri ) {
  1862.     if ( function_exists('curl_init') ) {
  1863.         $handle = curl_init();
  1864.         curl_setopt ($handle, CURLOPT_URL, $uri);
  1865.         curl_setopt ($handle, CURLOPT_CONNECTTIMEOUT, 1);
  1866.         curl_setopt ($handle, CURLOPT_RETURNTRANSFER, 1);
  1867.         $buffer = curl_exec($handle);
  1868.         curl_close($handle);
  1869.         return $buffer;
  1870.     } else {
  1871.         $fp = fopen( $uri, 'r' );
  1872.         if ( !$fp )
  1873.             return false;
  1874.         $linea = '';
  1875.         while( $remote_read = fread($fp, 4096) )
  1876.             $linea .= $remote_read;
  1877.         return $linea;
  1878.     }    
  1879. }
  1880.  
  1881. ?>